<?php
namespace App\Test;
use App\Models\Entity\Products;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Http\Message\Middleware\MiddlewareInterface;
use \Swoft\Bean\Annotation\Bean;
use Swoole\Exception;
use \Firebase\JWT\JWT;
/**
 * @Bean("TokenMiddWare")
 */
class TokenMiddWare implements MiddlewareInterface
{

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
//        获取token参数
        $getToken=$request->query("token",false);
//        验证是否存在不存在就异常
        if (!$getToken)throw new Exception("no token");
//        解析token
        $key="hboa";
        $userInfo=(array)JWT::decode($getToken,$key,["HS256"]);
//        塞入头变量
        $users=$userInfo['uname'];
        foreach($users as $key=>$value)
        {
            $request=  $request->withAddedHeader("token_".$key,$value);
        }
        $response = $handler->handle($request);
        return $response;
    }
}
